package com.geek.servlet;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Set;

/**
 * @Author: ysq
 * @Date: 2021/6/20
 * @Description: 在Tomcat环境, 编写Servlet程序, 通过JNDI获取JDBC DataSource
 * JNDI配置: src/main/resources/services/javax.servlet.ServletContainerInitializer
 * 数据源配: src/main/webapp/META-INF/context.xml
 */
public class ServletWebApplicationInitializer implements ServletContainerInitializer {
  @Override
  public void onStartup(final Set<Class<?>> c, final ServletContext ctx) throws ServletException {
    try {
      Context cxt = new InitialContext();
      DataSource dataSource = (DataSource) cxt.lookup("java:comp/env/jdbc/DemoDataSource");
      Connection connection = dataSource.getConnection();
      System.out.println("connection info: " + connection.toString());
    } catch (NamingException | SQLException e) {
      e.printStackTrace();
    }
  }
}
